package com.itheima.stock.service.impl;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.RedisConstants;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/23 15:53
 * @Description: 用户业务接口实现
 */
@Service
public class UserServiceImpl implements UserService {

    private final Cache cache;
    private final IdWorkers idWorkers;

    public UserServiceImpl(Cache cache, IdWorkers idWorkers) {
        this.cache = cache;
        this.idWorkers = idWorkers;
    }

    @Override
    public CaptchaVO generateCaptcha() {
        String captcha = RandomStringUtils.randomNumeric(4);
        String keySuffix = idWorkers.nextStrId();
        String redisKey = RedisKeyUtil.generateKey(RedisConstants.CAPTCHA_PREFIX, keySuffix);
        cache.set(redisKey, captcha, RedisConstants.CAPTCHA_EXPIRE);
        return CaptchaVO.builder().code(captcha).rkey(redisKey).build();
    }
}
